require 'rubygems'
require 'sinatra'
require 'sequel'
require 'json'

Sequel::Model.plugin(:schema)
Sequel.connect('sqlite://myapp.db')
class Memos < Sequel::Model
  unless table_exists?
    set_schema do
      primary_key :id
      string :body
    end
    create_table
  end
end

get '/api' do
  content_type :json
  JSON.unparse(Memos.all.map{|e| e.values})
end

post '/api' do
  res = Memos.insert(JSON.parse(request.body.read))
  content_type :json
  JSON.unparse :id =>  res
end

put '/api/:id' do
  id = params[:id]
  req = JSON.parse(request.body.read)

  m = Memos[id]
  m.body = req['body']
  m.save

  content_type :json
  JSON.unparse :id => id
end

delete '/api/:id' do
  id = params[:id]
  res = Memos[id].destroy
  content_type :json
  JSON.unparse :id => id
end
